<?php
/**
 * country.php
 *
 * Created on 2014-12-8
 * Create by LDD
 */
namespace haibao\cms\data;

use \haibao\cms\model\filter\FeaturePublish as FeaturePublishFilter;
use \haibao\frame\data\query\Condition as Condition;
use haibao\cms\model\data\SnsanyTopic as SnsanyTopicModel;
use haibao\cms\model\data\ZtSpecial as ZtSpecialModel;
use haibao\cms\model\data\ZtLog as ZtLogModel;
use haibao\cms\model\filter\SnsAnyTopic as SnsAnyTopicFilter;
use haibao\cms\model\filter\ZtSpecial as ZtSpecialFilter;
use haibao\cms\data\ZtSpecial as ZtSpecialData;
use haibao\cms\model\data\FeaturePublish as FeaturePublishModel;
use haibao\cms\model\data\FeatureIni as FeatureIniModel;

class FeaturePublish extends \haibao\cms\data\BaseMysql{
    const MOVE_DYNAMIC_DIRECT_UP = 1;
    const MOVE_DYNAMIC_DIRECT_DOWN = -1;
	
	private static $mongoDb = null;

	public function __construct(){
	    parent::__construct('\haibao\cms\model\data\FeaturePublish');
	}
	
	public function moveDynamic($offset,$defineId,$direct){
		if ($direct == self::MOVE_DYNAMIC_DIRECT_UP){
			$offset--;
		}
		
		if ($offset < 0){
			return ;
		}
		
		$sql = 'select * from FeatureItemGroupData where GroupDefineId=%s';
		$sql .= ' order by OrderNum asc,CreateTime asc limit %s,2';
		$result = $this->query($sql,array($defineId,$offset));
		
		$arr = array();
		while ($row = $result->fetch_assoc()){
			array_push($arr,$row);
		}
		
		if (count($arr) == 2){
			$sql = 'update FeatureItemGroupData set CreateTime="'.$arr[1]['CreateTime'].'",OrderNum='.$arr[1]['OrderNum'].' where Id='.$arr[0]['Id'];
			$this->query($sql);
			$sql = 'update FeatureItemGroupData set CreateTime="'.$arr[0]['CreateTime'].'",OrderNum='.$arr[0]['OrderNum'].' where Id='.$arr[1]['Id'];
			$this->query($sql);
		}
	}
	
	public function updateAppendDynamic($dynamicId,$order,$itemGroupModel){
		$sql = 'select CreateTime from FeatureItemGroupData where Id=%s';
		$result = $this->query($sql,array($dynamicId));
		$createTime = '';
		while ($row = $result->fetch_assoc()){
			$createTime = $row['CreateTime'];
		}
		
		$sql = 'update FeatureItemGroupData set OrderNum=OrderNum+1';
		$sql .= ' where GroupDefineId=%s and Id!=%s';
		$sql .= ' and (OrderNum>%s or (OrderNum=%s and CreateTime>%s))';
		
		$this->query($sql,array($itemGroupModel->GroupDefineId,$itemGroupModel->Id,$order,$order,$createTime));
	}
	
	public function getFeatureGroupBySerialId($serialIdArr,$limit){
	    $tempSql = '';
	    if($serialIdArr){
	        $serialIdStr = implode(',',$serialIdArr);
	        $tempSql = 'and A.SerialId in ('.$serialIdStr.')';
	    }
	    $sql = 'SELECT
                	*
                FROM
                	(
                		SELECT
                			A.FeatureName,
                			A.Id,
                			A.SerialId,
                			B.Url,
	                        B.ListTime,
	                        C.Filename
                		FROM
                			`FeatureDefine` AS A
                		INNER JOIN FeaturePublish AS B ON A.Id = B.FeatureDefineId
	                    INNER JOIN ImageLibrary as C ON C.Id = B.PictureId
                		WHERE
                			A.SerialId <> 0 '.$tempSql.'
                		AND B.IsH5 = 0
	                    AND B.IsList = 1
                		ORDER BY
                			B.ListTime DESC
                		LIMIT 12
                	) c
                GROUP BY
                	c.SerialId
                ORDER BY
                	c.ListTime DESC
                LIMIT '.$limit;
	    $result = $this->query($sql);
	    $featureNew = array();
	    while($row = $result->fetch_assoc()){
	        $featureNew[] = $row;
	    }
	    return $featureNew;
	}
	
	public function getFeatureGroupByClassId($classIdArr,$limit){
	    $tempSql = '';
	    if($classIdArr){
	        $classIdStr = implode(',',$classIdArr);
	        $tempSql = 'and A.ClassId in ('.$classIdStr.')';
	    }
	    $sql = 'SELECT
                	*
                FROM
                	(
                		SELECT
                			A.FeatureName,
                			A.Id,
                			A.ClassId,
                			B.Url,
	                        B.ListTime,
	                        C.Filename
                		FROM
                			`FeatureDefine` AS A
                		INNER JOIN FeaturePublish AS B ON A.Id = B.FeatureDefineId
	                    INNER JOIN ImageLibrary as C ON C.Id = B.PictureId
                		WHERE
                			A.ClassId <> 0 '.$tempSql.'
                		AND B.IsH5 = 0
	                    AND B.IsList = 1
                		ORDER BY
                			B.ListTime DESC
                		LIMIT 12
                	) c
                GROUP BY
                	c.ClassId
                ORDER BY
                	c.ListTime DESC
                LIMIT '.$limit;
	    $result = $this->query($sql);
	    $featureNew = array();
	    while($row = $result->fetch_assoc()){
	        $featureNew[] = $row;
	    }
	    return $featureNew;
	}
	
	public function getGrade($featureIds){
		$data = array();
		$sql = 'SELECT FeatureId,sum(DesignerGrade) AS SumDesigner,avg(DesignerGrade) AS AvgDesigner';
		$sql .= ' FROM FeatureGrade WHERE';
		$sql .= ' FeatureId in ('.implode(',',$featureIds).') and DesignerGrade != 0 group by FeatureId';
		
		$result = $this->query($sql);
		while ($result->fetch_assoc()){
			$featureId = $result->getData('FeatureId');
			if (!isset($data[$featureId])){
				$data[$featureId] = array('SumDesigner'=>0,'AvgDesigner'=>0,'SumHtml'=>0,'AvgHtml'=>0,);
			}
			
			$data[$featureId]['SumDesigner'] = round($result->getData('SumDesigner'),2);
			$data[$featureId]['AvgDesigner'] = round($result->getData('AvgDesigner'),2);
		}
		
		$sql = 'SELECT FeatureId,sum(HtmlGrade) AS SumHtml,avg(HtmlGrade) AS AvgHtml';
		$sql .= ' FROM FeatureGrade WHERE';
		$sql .= ' FeatureId in ('.implode(',',$featureIds).') and HtmlGrade != 0 group by FeatureId';
		$result = $this->query($sql);
		while ($result->fetch_assoc()){
			$featureId = $result->getData('FeatureId');
			if (!isset($data[$featureId])){
				$data[$featureId] = array('SumDesigner'=>0,'AvgDesigner'=>0,'SumHtml'=>0,'AvgHtml'=>0,);
			}
				
			$data[$featureId]['SumHtml'] = round($result->getData('SumHtml'),2);
			$data[$featureId]['AvgHtml'] = round($result->getData('AvgHtml'),2);
		}
		
		return $data;
	}
	
	public function updateStatisticEndTime($id,$statisticEndTime){
		$sql = 'select count(*) as num from FeatureStatistic where FeatureId=%s';
		$result = $this->query($sql,array($id));
		$num = 0;
		while ($result->fetch_assoc()){
			$num = $result->getData('num');
		}
		
		if ($num){
			$sql = 'update FeatureStatistic set StatisticEndTime=%s where FeatureId=%s';
			$this->query($sql,array($statisticEndTime,$id));
		}else{
			$sql = 'insert into FeatureStatistic(FeatureId,StatisticEndTime) values(%s,%s)';
			$this->query($sql,array($id,$statisticEndTime));
		}
	}
	
	public function getFeaturePublishByIds($featureIds){
	    $sql = 'select Id,PublishTime from FeaturePublish where Id in ('.implode(',',$featureIds).') and Status <> 0';
	    $result = $this->query($sql,$featureIds);
	    $infoList = array();
	    while($row = $result->fetch_assoc()){
	        $infoList[$row['Id']] = $row['PublishTime'];
	    }
	    return $infoList;
	}
	
	public function searchIdsByKeywordFilter($filter){
		$ids = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		
		if (!empty($result['matches'])){
			$filter->getPager()->setResultCount($result['total']);
			foreach ($result['matches'] as $match){
				array_push($ids,$match['attrs']['recordid']);
			}
		}
		
		return $ids;
	}
	
	private function getDynamicOrderStr($type){
		$str = '';
		switch ($type){
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_CREATE_TIME_ASC:
				$str = 'createtime,1';
				break;
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_CREATE_TIME_DESC:
				$str = 'createtime,-1';
				break;
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_SHOW_TIME_ASC:
				$str = 'showtime,1';
				break;
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_SHOW_TIME_DESC:
				$str = 'showtime,-1';
				break;
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_NUMBER_ASC:
				$str = 'order,1';
				break;
			case \haibao\cms\model\data\FeatureDynamicDefineList::ORDER_TYPE_NUMBER_DESC:
				$str = 'order,-1';
				break;
		}
		
		return $str;
	}
	
	public function getAllDynamicListByFeatureId($featureDefineId){
		$data = array();
		$sql = 'select t1.* from FeatureDynamicDefineList t1';
		$sql .= ' inner join FeatureGroupDefine t2 on t1.DefineId = t2.Id';
		$sql .= ' where t2.FeatureId='.$this->escape($featureDefineId);
		$result = $this->query($sql);
		$parameters = array();
		$codes = array();
		while ($result->fetch_assoc()){
			array_push($parameters,array(
				'code'=>$result->getData('Code'),
				'currentPage'=>$result->getData('CurrentPage'),
				'pageSize'=>$result->getData('PageSize'),
				'order'=>$this->getDynamicOrderStr($result->getData('Order'))
			));
			array_push($codes,$result->getData('Code'));
		}
		
		if ($parameters){
			$result = $this->getDynamicList($featureDefineId, $parameters);
			foreach ($codes as $code){
				if (empty($result[$code])){
					$data[$code] = array();
				}else{
					$data[$code] = $result[$code]['data'];
				}
			}
		}
		
		return $data;
	}
	
	public function addShareCount($oldFeatureId,$type){
		if ($featureId = $this->getFeatureIdByOldFeatureId(new FeaturePublishModel(), $oldFeatureId)){
			$updateColumnName = '';
			switch ($type){
				case \haibao\cms\model\data\FeaturePublish::SHARE_TYPE_SINA_WEIBO:
					$updateColumnName = 'SinaShareCount';
					break;
				case \haibao\cms\model\data\FeaturePublish::SHARE_TYPE_QQ_WEIBO:
					$updateColumnName = 'QQWeiboShareCount';
					break;
				case \haibao\cms\model\data\FeaturePublish::SHARE_TYPE_QQ_ZONE:
					$updateColumnName = 'QQZoneShareCount';
					break;
				case \haibao\cms\model\data\FeaturePublish::SHARE_TYPE_RENREN:
					$updateColumnName = 'RenrenShareCount';
					break;
				case \haibao\cms\model\data\FeaturePublish::SHARE_TYPE_WEIXIN:
					$updateColumnName = 'WeixinShareCount';
					break;
			}
			if ($updateColumnName){
				$sql = "update FeaturePublish set {$updateColumnName}={$updateColumnName}+1 where Id={$featureId}";
				$this->query($sql);
			}
		}
	}
	
	public function addPv($oldFeatureId){
		if ($newFeatureId = $this->getFeatureIdByOldFeatureId(new FeaturePublishModel(), $oldFeatureId)){
			$cache = new \haibao\cms\cache\Feature();
			$cache->addFeaturePv($newFeatureId);
		}
	}

	public function getFeaturePvCount($featureId){
		$num = 0;
		$sql = "select ShowPvCount from FeaturePublish where Id = %s";
		$result = $this->query($sql,array($featureId));
		while($result->fetch_assoc()){
			$num = $result->getData('ShowPvCount');
		}
		return $num;
	}

	
	public function checkCopying($featureId){
		$isCopying = false;
		$sql = 'select count(*) as num from FeatureCopyPlan where FeatureId='.$featureId.' and Status = 0';
		$result = $this->query($sql);
		while ($result->fetch_assoc()){
			$num = $result->getData('num');
			if ($num){
				$isCopying = true;
			}
		}
		
		return $isCopying;
	}
	
	public function copyFeatureDynamic($featureDefineId,$otherFeatureDefineId){
		$sql = 'select count(*) as num from FeatureGroupDefine where FeatureId='.$otherFeatureDefineId;
		$defineResult = $this->query($sql);
		$needCopy = false;
		if ($defineResult->getMysqlResult()){
			while ($defineResult->fetch_assoc()){
				$num = $defineResult->getData('num');
				if ($num){
					$needCopy = true;
				}
			}
		}
		
		$sql = 'select count(*) as num from FeatureCopyPlan where FeatureId='.$featureDefineId.' and CopyId='.$otherFeatureDefineId;
		$result = $this->query($sql);
		if ($result->fetch_assoc()){
			$num = $result->getData('num');
			if ($num){
				$needCopy = false;
			}
		}
		
		if ($needCopy){
			$sql = 'insert into FeatureCopyPlan(FeatureId,CopyId,Status) values('.$featureDefineId.','.$otherFeatureDefineId.',0)';
			$this->query($sql);
		}
	}
	
	public function updateFeaturePvCount($featureId,$num){
		$sql = 'update FeaturePublish set ShowPvCount=%s where Id=%s';
		$this->query($sql,array($num,$featureId));
	}
	
	public function updateFeatureCommentNum($featureId,$num){
		$sql = 'update FeaturePublish set CommentCount=CommentCount+'.$num.' where Id=%s';
		$this->query($sql,array($featureId));
	}
	
	public function subtractCommentNum($featureId){
		$sql = 'update FeaturePublish set CommentCount=CommentCount-1 where Id=%s';
		$this->query($sql,array($featureId));
	}
	
	public function getFeaturePvCountByIds($featureIds){
		$reault = array();
		$ids = (array)$featureIds;
		$featureIdStr = implode(',', $ids);
		$str = preg_replace('/(\d+)/', '%s', $featureIdStr);
		$sql = "select Id,PvCount,ShowPvCount from FeaturePublish where Id IN (".$str.")";
		$data = $this->query($sql,$ids);
		while ($data->fetch_assoc()){
			$id = $data->getData('Id');
			$result[$id]['PvCount'] = $data->getData('PvCount');
			$result[$id]['ShowPvCount'] = $data->getData('ShowPvCount');
		}
		return $result;
	}
	
	public function copyFeatureParam($featureDefineId,$otherFeatureDefineId){
		$sql = <<<EOT
INSERT INTO FeatureParam (
	FeatureId,
	Code,
	Name,
	Value,
	ContentType,
	ParamType,
	CreateTime,
	CreateBy
)
select
	{$featureDefineId},
	Code,
	Name,
	Value,
	ContentType,
	ParamType,
	CreateTime,
	CreateBy
from
	FeatureParam
where
	FeatureId={$otherFeatureDefineId}
	and Code not in (select Code from FeatureParam where FeatureId={$featureDefineId})
EOT;
	$this->query($sql);
	}
	
	public function copyFeatureIni($featureId,$otherFeatureId){
		$sql = <<<EOT
INSERT INTO FeatureIni (
	FeatureId,
	Title,
	Description,
	Keywords,
	Vote,
	HaibaoHeader,
	HaibaoBottom,
	GoTop,
	PcShare,
	WeixinShare,
	Dynamic,
	Record,
	WeixinShareTitle,
	WeixinShareDesc,
	WeixinShareImg,
	WeixinShareUrl
)
select
	{$featureId},
	Title,
	Description,
	Keywords,
	Vote,
	HaibaoHeader,
	HaibaoBottom,
	GoTop,
	PcShare,
	WeixinShare,
	Dynamic,
	Record,
	WeixinShareTitle,
	WeixinShareDesc,
	WeixinShareImg,
	WeixinShareUrl
from
	FeatureIni
where
	FeatureId={$otherFeatureId}
EOT;
	$this->query($sql);
	}
	
	public function getImgList($featureId,$page,$pageSize,$orderType){
		$data = array('count'=>0,'data'=>array());
		$countSql = 'select count(*) as num from FeatureImg where Status = 1 and FeatureId = %s';
		$result = $this->query($countSql,array($featureId));
		while ($result->fetch_assoc()){
			$data['count'] = $result->getData('num');
		}
		
		if ($data['count']){
			$sql = 'select t1.*,t2.Count from FeatureImg t1 left join FeatureVote t2 on t1.Id=t2.VoteName and t1.FeatureId = t2.FeatureId where t1.Status = 1';
			$sql .= ' and t1.FeatureId=%s';
			if ($orderType == 1){
				$sql .= ' order by t1.CreateTime desc';
			}
			else if ($orderType == 2){
				$sql .= ' order by t2.Count desc';
			}
			else if ($orderType == 3){
				$sql .= ' order by t1.CreateTime asc';
			}
			else if ($orderType == 4){
				$sql .= ' order by t2.Count asc';
			}
			
			$sql .= ' limit '.($page-1)*$pageSize.','.$pageSize;
			$result = $this->query($sql,array($featureId));
			while ($row = $result->fetch_assoc()){
				array_push($data['data'],array(
					'id'=>$result->getData('Id'),
					'borderImg'=>$result->getData('BorderImg'),
					'count'=>intval($result->getData('Count'))
				));
			}
		}
		
		return $data;
	}
	
	public function setImgBorder($id,$borderImg){
		$sql = 'update FeatureImg set BorderImg=%s,Status=1 where Id=%s';
		$this->query($sql,array($borderImg,$id));
	}
	
	public function getImgById($id){
		$content = null;
		$sql = 'select * from FeatureImg where Id=%s';
		$result = $this->query($sql,array($id));
		while ($row = $result->fetch_assoc()){
			$content = $result->getData('Content');
		}
		
		return $content;
	}
	
	public function addImg($content,$featureId){
		$sql = 'insert into FeatureImg(FeatureId,Content,CreateTime,Status) values('.$featureId.',"'.$content.'","'.date('Y-m-d H:i:s').'",0)';
		$this->query($sql);
		$id = $this->getDb()->insert_id;
		
		return $id;
	}
	
	public function addFeatureRecord($itemModels,$featureId,$defineId){
		$this->beginTranscation();
		
		try{
			if (!$defineId){
				$model = new \haibao\cms\model\data\FeatureRecordDefine();
				$model->CreateTime = new \DateTime();
				$model->FeatureId = $featureId;
				$this->add($model);
				$defineId = $model->Id;
			}
			
			foreach ($itemModels as $itemModel){
				$itemModel->DefineId = $defineId;
			}
			$this->addAll($itemModels);
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
		
		return $defineId;
	}
	
	public function updateFeatureIni($featureId,$id,$arrSet){
		//兼容旧数据
		if (!$id){
			$sql = 'select Id from FeatureIni where FeatureId=%s';
			$result = $this->query($sql,array($featureId));
			if ($result && ($row = $result->fetch_assoc())){
				$id = $row['Id'];
			}
			else{
				$model = new FeatureIniModel();
				$model->FeatureId = $featureId;
				$this->add($model);
				$id = $model->Id;
			}
		}
		
		$this->setModelName('\haibao\cms\model\data\FeatureIni');
		$this->updateById($id, $arrSet);
		$this->setModelName('\haibao\cms\model\data\FeaturePublish');
	}
	
	public function updateFeatureParamById($id,$arrSet){
		if ($id){
			$this->setModelName('\haibao\cms\model\data\FeatureParam');
			$this->updateById($id, $arrSet);
			$this->setModelName('\haibao\cms\model\data\FeaturePublish');
		}
	}
	
	public function addDynamicDefine($model){
		$this->beginTranscation();
		
		try{
			$this->add($model);
			foreach ($model->Items as $item){
				$item->GroupDefineId = $model->Id;
			}
			foreach ($model->DefineLists as $list){
				$list->DefineId = $model->Id;
			}
			$this->addAll($model->DefineLists);
			$this->addAll($model->Items);
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function updateDynamicDefine($model){
		$this->beginTranscation();
		
		try{
			$sql = 'update FeatureGroupDefine set GroupName=%s where Id = '.$model->Id;
			$this->query($sql,array($model->GroupName));	
			
			//list删除后更新
			$sql = 'delete from FeatureDynamicDefineList where DefineId=%s';
			$this->query($sql,array($model->Id));
			$this->addAll($model->DefineLists);
			
			//items，更新，添加，删除及data
			$filter = new \haibao\cms\model\filter\FeatureGroupDefineItem();
			$filter->where(
				\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_GROUP_DEFINE_ID,
				Condition::CONDITION_EQUAL,
				$model->Id
			);
			$result = self::getAll($filter);
			$addData = array();
			$updateData = array();
			$delIds = array();
			$ids = array();
			foreach ($model->Items as $item){
				if ($item->Id){
					array_push($ids,$item->Id);
					array_push($updateData,$item);
				}
				else{
					array_push($addData,$item);
				}
			}
			if ($result){
				foreach ($result as $value){
					if (!in_array($value->Id,$ids)){
						array_push($delIds,$value->Id);
					}
				}
			}
			
			if ($addData){
				$this->addAll($addData);
			}
			
			if ($updateData){
				$this->setModelName('\haibao\cms\model\data\FeatureGroupDefineItem');
				foreach ($updateData as $data){
					$arrSet = array(
							\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_ITEM_CODE=>$data->ItemCode,
							\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_ITEM_NAME=>$data->ItemName,
							\haibao\cms\model\filter\FeatureGroupDefineItem::CONDITION_FIELD_NAME_ITEM_TYPE=>$data->ItemType
					);
					$this->updateById($data->Id, $arrSet);
				}
				$this->setModelName('\haibao\cms\model\data\FeatureGroupDefine');
			}
			
			if ($delIds){
				$sql = 'delete from FeatureGroupDefineItem where Id in ('.implode(',',$delIds).')';
				$this->query($sql);
				$sql = 'delete from FeatureGroupDefineItemData where GroupDefineItemId in ('.implode(',',$delIds).')';
				$this->query($sql);
			}
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function delDynamicDefine($defineId){
		$this->beginTranscation();
		
		try{
			$sql = 'delete from FeatureGroupDefine where id=%s';
			$this->query($sql,array($defineId));
			$sql = 'delete from FeatureGroupDefineItem where GroupDefineId=%s';
			$this->query($sql,array($defineId));
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function delParamById($paramId){
		$sql = 'delete from FeatureParam where id=%s';
		$this->query($sql,array($paramId));
	}
	
	public function updateFeatureParam($id,$arrSet){
		if ($id){
			$this->setModelName('\haibao\cms\model\data\FeatureParam');
			$this->updateById($id, $arrSet);
			$this->setModelName('\haibao\cms\model\data\FeaturePublish');
		}
	}
	
	public function addFeatureIni($model){
		$this->beginTranscation();
		
		try{
			$sql = 'delete from FeatureIni where FeatureId=%s';
			$this->query($sql,array($model->FeatureId));
			$this->add($model);
		}
		catch (\Exception $e){
			$this->rollBack();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	/**
	 * 修改专题显示状态
	 */
	public function listFeature($featureId,$isList){
		if ($oldFeatureId = $this->getDataMigration(new FeaturePublishModel(), $featureId)){
			$arrSet = array(
				FeaturePublishFilter::CONDITION_FIELD_NAME_IS_LIST=>$isList,
				FeaturePublishFilter::CONDITION_FIELD_NAME_UPDATE_TIME=>new \DateTime()
			);
			
			if ($isList == FeaturePublishModel::IS_LIST_ENABLE){
				$oldArrSet = array(
						ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_SHOW=>ZtSpecialModel::LIST_SHOW_ENABLE,
						ZtSpecialFilter::CONDITION_FIELD_NAME_STATUS=>ZtSpecialModel::STATUS_ENABLE,
				);
			}else{
				$oldArrSet = array(
						ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_SHOW=>ZtSpecialModel::LIST_SHOW_DISABLE,
				);
			}
			
			$ztData = new ZtSpecialData();
			
			$this->beginTranscation();
			try {
				$this->updateById($featureId, $arrSet);
				$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
				$ztData->updateById($oldFeatureId, $oldArrSet);
			}
			catch (\Exception $e){
				$this->rollback();
				throw $e;
			}
			
			$this->endTranscation();
		}
	}
	
	public function getDynamicList($featureDefineId,$parameters){
		$data = array();
		if ($parameters){
			
			//循环查询，获取每个分类的总数及分页记录
			foreach ($parameters as $parameter){
				$groupCode = $parameter['code'];
				$currentPage = $parameter['currentPage'];
				$pageSize = $parameter['pageSize'];
				$resultCount = 0;
				$orderStr = '';
				/* if (!empty($parameter['order'])){
					$arr = explode(',',$parameter['order']);
					$orderColumn = strtolower($arr[0]);
					if ($orderColumn == 'createtime'){
						$orderColumn = 'a1.CreateTime';
					}else if ($orderColumn == 'showtime'){
						$orderColumn = 'a1.ShowTime';
					}else if ($orderColumn == 'order'){
						$orderColumn = 'a1.OrderNum';
					}
					$orderStr .= ' order by '.$orderColumn;
					if (count($arr) > 1 && $arr[1] == '1'){
						$orderStr .= ' asc';
					}
					else{
						$orderStr .= ' desc';
					}
					
				}else{
					$orderStr .= ' order by a1.OrderNum asc,a1.CreateTime asc';
				} */
				$orderStr .= ' order by a1.OrderNum asc,a1.CreateTime asc';
				
				$countSql = ' select count(*) as num from FeatureItemGroupData a1';
				$countSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
				$countSql .= ' inner join FeatureDynamicDefineList a3 on a3.DefineId = a2.Id';
				$countSql .= ' where a2.FeatureId=%s and a3.Code=%s';
				
				$result = $this->query($countSql,array($featureDefineId,$groupCode));
				if ($result && ($row = $result->fetch_assoc())){
					$resultCount = $row['num'];
				}
				
				if ($resultCount > 0){
					$innerSql = ' select a1.Id from FeatureItemGroupData a1';
					$innerSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
					$innerSql .= ' inner join FeatureDynamicDefineList a3 on a3.DefineId = a2.Id';
					$innerSql .= ' where a2.FeatureId=%s';
					$innerSql .= ' and a3.Code=%s';
					$innerSql .= $orderStr; 
					$innerSql .= ' limit %s,%s';
						
					$searchSql = 'select a5.Code,a1.ShowTime,a1.CreateTime,a4.ItemCode,a4.ItemType,a3.ItemValue,a1.Id,a4.Id as ItemId from FeatureItemGroupData a1';
					$searchSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
					$searchSql .= ' inner join FeatureGroupDefineItemData a3 on a1.Id= a3.ItemGroupDataId';
					$searchSql .= ' inner join FeatureGroupDefineItem a4 on a3.GroupDefineItemId = a4.Id';
					$searchSql .= ' inner join FeatureDynamicDefineList a5 on a5.DefineId = a2.Id';
					$searchSql .= ' inner join ('.$innerSql.') s on s.Id = a1.Id';
					$searchSql .= ' where a5.Code=%s';
	
					if ($result = $this->query($searchSql,array($featureDefineId,$groupCode,(($currentPage-1)*$pageSize),$pageSize,$groupCode))){
						while ($row = $result->fetch_assoc()){
							$groupCode = $row['Code'];
							$id = $row['Id'];
	
							if (!isset($data[$groupCode])){
								$data[$groupCode] = array(
										'currentPage'=>$currentPage,
										'pageSize'=>$pageSize,
										'rowCount'=>$resultCount,
										'pageCount'=>ceil($resultCount/$pageSize),
										'data'=>array()
								);
							}
	
							if (!isset($data[$groupCode]['data'][$id])){
								$data[$groupCode]['data'][$id] = array();
								$data[$groupCode]['data'][$id]['id'] = $id;
								$data[$groupCode]['data'][$id]['createTime'] = $row['CreateTime'];
								$data[$groupCode]['data'][$id]['showTime'] = $row['ShowTime'];
							}
							
							$data[$groupCode]['data'][$id][$row['ItemCode']] = $row['ItemValue'];
						}
					}
					
					if (isset($data[$groupCode])){
						$data[$groupCode]['data'] = array_values($data[$groupCode]['data']);
					}
				}
			}
		}
		
		return $data;
	}
	
	public function delDynamic($itemGroupId){
		if ($itemGroupId){
			$this->beginTranscation();
			try{
				$sql = 'delete from FeatureItemGroupData where Id=%s';
				$this->query($sql,array($itemGroupId));
				$sql = 'delete from FeatureGroupDefineItemData where ItemGroupDataId=%s';
				$this->query($sql,array($itemGroupId));
			}
			catch (\Exception $e){
				$this->rollback();
				throw $e;
			}
			$this->endTranscation();
		}
	}
	
	public function updateFeatureDynamic($itemDataModels,$itemGroupId,$showTime){
		foreach ($itemDataModels as $itemDataModel){
			$itemDataModel->Id = null;
		}
		
		$this->beginTranscation();
		try{
			$sql = 'delete from FeatureGroupDefineItemData where ';
			foreach ($itemDataModels as $key=>$value){
				if ($key){
					$sql .= ' or ';
				}
				$sql .= ' (ItemGroupDataId='.$value->ItemGroupDataId.' and GroupDefineItemId='.$value->GroupDefineItemId.')';
			}
			
			$this->query($sql);
			
			$this->addAll($itemDataModels);
			
			if (!$showTime){
				$showTime = new \DateTime();
			}
			$sql = 'update FeatureItemGroupData set ShowTime=%s where Id=%s';
			$this->query($sql,array($showTime,$itemGroupId));
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function vote($id,$name){
		$count = 0;
		$sql = 'select * from FeatureVote where FeatureId=%s and VoteName=%s';
		$result = $this->query($sql,array($id,$name));
		
		if ($row = $result->fetch_assoc()){
			$sql = 'update FeatureVote set Count=Count+1 where FeatureId=%s and VoteName=%s';
			$this->query($sql,array($id,$name));
			$count = $row['Count'] + 1;
		}else{
			$sql = 'insert into FeatureVote(FeatureId,VoteName,Count) values(%s,%s,1)';
			$this->query($sql,array($id,$name));
			$count = 1;
		}
		
		return $count;
	}
	
	public function unVote($id,$name){
		$count = 0;
		$sql = 'select * from FeatureVote where FeatureId=%s and VoteName=%s';
		$result = $this->query($sql,array($id,$name));
		
		if ($row = $result->fetch_assoc()){
			$sql = 'update FeatureVote set Count = Count - 1 where FeatureId=%s and VoteName = %s';
			$this->query($sql,array($id,$name));
			$count = $row['Count'] - 1;
		}
		
		return $count;
	}
	
	public function updateOldFeatureRecord($featureModel,$oldFeature){
		$author = '';
		$picName = '';
		$userData = new \haibao\cms\data\User();
		$userModel = $userData->getUserById($featureModel->CreateBy);
		if ($userModel){
			$author = $userModel->UserName;
		}
		$ztArrSet = array(
			ZtSpecialFilter::CONDITION_FIELD_NAME_UPDATE_DATE=>$featureModel->UpdateTime,
			ZtSpecialFilter::CONDITION_FIELD_NAME_URL=>$featureModel->Url,
			ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_DATE=>$featureModel->ListTime,
		);
		$snsArrSet = array(
			SnsAnyTopicFilter::CONDITION_FIELD_NAME_DESC=>str_replace('_海报时尚网','',$featureModel->FeatureDefine->FeatureName),
			SnsAnyTopicFilter::CONDITION_FIELD_NAME_URL=>$featureModel->Url
		);
		
		$ztLogModel = new ZtLogModel();
		$ztLogModel->UserId = $author;
		$ztLogModel->Content = '编辑专题';
		$ztLogModel->AddTime = date('Y-m-d H:i:s');
		
		$ztData = new ZtSpecialData();
		$oldFeature = $ztData->getOneById($oldFeature->Id);
		
		try {
			$ztData->beginTranscation();
				
			$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
			$ztData->updateById($oldFeature->Id, $ztArrSet);
			
			$ztData->setModelName('\haibao\cms\model\data\SnsAnyTopic');
			$ztData->updateById($oldFeature->SnsTid,$snsArrSet);
			
			$ztLogModel->ZtsId = $oldFeature->Id;
			$ztData->add($ztLogModel);
			$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
			
			$ztData->endTranscation();
		}
		catch (\Exception $e){
			$ztData->rollback();
			throw $e;
		}
	}
	
	/**
	 * 同步专题记录到旧数据库
	 * @param \haibao\cms\model\data\FeaturePublish $featureModel
	 */
	public function saveOldFeatureRecord($featureModel){
		$id = null;
		$author = '';
		$picName = '';
		$userData = new \haibao\cms\data\User();
		$userModel = $userData->getUserById($featureModel->CreateBy);
		if ($userModel){
			$author = $userModel->UserName;
		}
		
		//保存图片到旧专题地址
		if ($featureModel->PictureId){
			/* $imageData = new \haibao\cms\data\ImageLibrary();
			$image = $imageData->getImgageByMongo($featureModel->PictureId);
			$common = new \haibao\cms\common\ArticleContent();
			$picName = $common->replaceImageLink($image->file['Filename'],0,0,100,0); */
			$imageData = new \haibao\cms\data\ImageLibrary();
			$image = $imageData->getImageById($featureModel->PictureId);
			if ($image){
				$picName = \haibao\cms\web\common\PublishArticle::getImageRealUrl($image[0]->Filename,0,0100);
			}
		}
		
		$snsModel = new SnsanyTopicModel();
		$ztModel = new ZtSpecialModel();
		$ztLogModel = new ZtLogModel();
		
		$snsModel->Url = $featureModel->Url;
		$snsModel->Desc = str_replace('_海报时尚网','',$featureModel->FeatureDefine->FeatureName);
		
		$ztModel->Channel = 0;
		$ztModel->Title = $featureModel->FeatureDefine->FeatureName;
		$ztModel->Url = $featureModel->Url;
		$ztModel->Author = $author;
		$ztModel->Keywords = $featureModel->Keywords ? $featureModel->Keywords : '';
		$ztModel->Description = $featureModel->Description;
		$ztModel->EditTag = 0;
		$ztModel->Template = '';
		$ztModel->CreateDate = $featureModel->CreateTime;
		$ztModel->UpdateDate = $featureModel->UpdateTime;
		$ztModel->Tag = $featureModel->ClassId;
		$ztModel->Pic = $picName;
		$ztModel->ListDate = $featureModel->ListTime;
		$ztModel->TagName = $featureModel->CommentTag;
		$ztModel->ZtVideoCate = $featureModel->ColumnId;
		$ztModel->Status = ZtSpecialModel::STATUS_ENABLE;
		$ztModel->PollValid = $this->formatTime($featureModel->VoteStartTime).'~'.$this->formatTime($featureModel->VoteEndTime);
		$ztModel->CommentDate = $this->formatTime($featureModel->CommentStartTime).'~'.$this->formatTime($featureModel->CommentEndTime);
		$ztModel->ListDate = $featureModel->ListTime;
		
		$ztLogModel->UserId = $author;
		$ztLogModel->Content = '新建专题';
		$ztLogModel->AddTime = date('Y-m-d H:i:s');
		
		$ztData = new VideoCateData();
		try {
			$ztData->beginTranscation();
			
			$ztData->add($snsModel);
			
			$ztModel->SnsTid = $snsModel->Id;
			$ztData->add($ztModel);
			
			$ztLogModel->ZtsId = $ztModel->Id;
			$ztData->add($ztLogModel);
			
			$id = $ztModel->Id;
			$ztData->endTranscation();
		}
		catch (\Exception $e){
			$ztData->rollback();
			throw $e;
		}
		
		return $id;
	}
	
	public function getVideoCates($filter){
		$videoCateData = new VideoCateData();
		
		return $videoCateData->getAll($filter);
	}
	
	public function updateFeature($id,$arrSet){
		try{
			$this->beginTranscation();
			$this->updateById($id, $arrSet);
			
			if (isset($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_TAGS])){
				$this->saveFeatureTagRelation($id,$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_TAGS],true);		
			}
			if (isset($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_EVENTS])){
				$this->saveFeatureEventRelation($id,$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_EVENTS],true);
			}
				
			$this->endTranscation();
		}
		catch (Exception $e){
			$this->rollBack();
			throw $e;
		}
	}
	
	/**
	 * 添加专题
	 * @param \haibao\cms\model\data\FeatureDefine $model
	 */
	public function addFeature($model){
		$this->add($model);
		if ($model->Events){
			$this->saveFeatureEventRelation($model->Id,$model->Events);
		}
		if ($model->Tags){
			$this->saveFeatureTagRelation($model->Id,$model->Tags);
		}
		if ($model->FeaturePublishes){
			foreach ($model->FeaturePublishes as $featurePublish){
				$featurePublish->FeatureDefineId = $model->Id;
				$this->add($featurePublish);
			}
		}
	}
	
	public function saveFeatureEventRelation($featureId,$eventIds,$isEdit = false){
		if ($isEdit){
			$sql = 'delete from FeatureEvent where FeatureId=%s';
			$this->query($sql,array($featureId));
		}
		
		if ($eventIds){	
			$sql = 'insert into FeatureEvent(FeatureId,EventId) values';
			$sqlArr = array();
			$param = array();
			foreach ($eventIds as $eventId){
				array_push($sqlArr,'(%s,%s)');
				array_push($param,$featureId);
				array_push($param,$eventId);
			}
			$sql .= implode(',',$sqlArr);
			$this->query($sql,$param);
		}
	}
	
	public function saveFeatureTagRelation($featureId,$tagIds,$isEdit = false){
		if ($isEdit){
			$sql = 'delete from FeatureTag where FeatureId=%s';
			$this->query($sql,array($featureId));
		}
		
		if ($tagIds){		
			$sql = 'insert into FeatureTag(FeatureId,TagId) values';
			$sqlArr = array();
			$param = array();
			foreach ($tagIds as $tagId){
				array_push($sqlArr,'(%s,%s)');
				array_push($param,$featureId);
				array_push($param,$tagId);
			}
			$sql .= implode(',',$sqlArr);
			$this->query($sql,$param);
			
			//TT addtime 2015.11.26判断标签是否包含品牌、明星、设计师，如果有，修改品牌、明星或设计师表的updatetime
			//修改品牌库某品牌记录的修改日期
			$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
			$this->query ($sql);
			
			//修改明星库某明星记录的修改日期
			$sql = "update Celebrity set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
			$this->query ($sql);
			
			//TODO 修改设计师库某设计师记录的修改日期
			$sql = "update Designer set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
			$this->query ($sql);
		}
	}
	
	public function getTagIds($featureId){
		$sql = "select TagId from FeatureTag where FeatureId = %s";
		$result = $this->query($sql,array($featureId));
		$tagIds = array();
		while($result->fetch_assoc()){
			$tagIds[] = $result->getData('TagId');
		}
		
		return $tagIds;
	}
	
	public function storeFeatureZip($bytes,$parameters = array()){
		return self::getFeatureMongoBb()->storeFeatureZip($bytes, $parameters);
	}
	
	public function getFeatureZipById($id){
		return self::getFeatureMongoBb()->getFeatureZipById($id);
	}
	
	public function getFeatureZipByIds($ids){
		return self::getFeatureMongoBb()->getFeatureZipByIds($ids);
	}
	
	public function delFeatureZipById($id){
		return self::getFeatureMongoBb()->delFeatureZipById($id);
	}
	
	public function getFeatureImgByIds($ids){
		return self::getFeatureMongoBb()->getFeatureImgByIds($ids);
	}
	
	public function storeFeatureImg($bytes,$parameters = array()){
		return self::getFeatureMongoBb()->storeFeatureImg($bytes, $parameters);
	}
	
	public function delFeatureImgById($id){
		return self::getFeatureMongoBb()->delFeatureImgById($id);
	}
	
	private static function getFeatureMongoBb(){
		if (!self::$mongoDb){
			self::$mongoDb = new FeatureMongo();
		}
		
		return self::$mongoDb;
	}
	
	public function addDataMigrationMap($model,$oldId){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldId));
	}
	
	public function getDataMigration($model,$newPrimaryKey){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		$tableName = $model->getTableName();
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}
	
	public function getFeatureIdByOldFeatureId($model,$oldFeatureId){
		$primaryKey = null;
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		$tableName = $model->getTableName();
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and OldPrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$oldFeatureId
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$primaryKey = $result->getData('PrimaryKey');
		}
		
		return $primaryKey;
	}
	
	private function formatTime($dateTime,$formatStr = 'Y-m-d H:i:s'){
		$date = '';
		if ($dateTime instanceof \DateTime && $dateTime->format('Y') != '-0001'){
			$date = date($formatStr);
		}
	
		return $date;
	}
}

class VideoCateData extends \haibao\cms\data\BaseMysql{
	public function __construct(){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
	}
}


class FeatureMongo extends \haibao\cms\data\BaseMongoDb{
	const DB_NAME_FEATURE_ZIP = 'featurezip';
	const DB_NAME_FEATURE_IMG = 'featureimg';
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\FeaturePublish');
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MONGODB_FEATURE );
	}
	
	public function delFeatureImgById($id){
		$this->removeFileById(self::DB_NAME_FEATURE_IMG, $id);
	}
	
	public function storeFeatureImg($bytes,$parameters){
		return $this->storeBytes(self::DB_NAME_FEATURE_IMG, $bytes, $parameters);
	}
	
	public function getFeatureImgByIds($ids){
		$data = array();
		if ($ids){
			$mongoIds = array();
			foreach ($ids as $id){
				array_push($mongoIds,$this->getMongoId($id));
			}
			
			$cursor = $this->getFiles(self::DB_NAME_FEATURE_IMG,array('_id'=>array('$in'=>$mongoIds)));
			if ($cursor){
				foreach ($cursor as $key=>$value){
					array_push($data,$value);
				}
			}
		}
		
		return $data;
	}
	
	public function getFeatureZipByIds($ids){
		$data = array();
		if ($ids){
			$mongoIds = array();
			foreach ($ids as $id){
				array_push($mongoIds,$this->getMongoId($id));
			}
			
			$cursor = $this->getFiles(self::DB_NAME_FEATURE_ZIP,array('_id'=>array('$in'=>$mongoIds)));
			if ($cursor){
				foreach ($cursor as $key=>$value){
					array_push($data,$value);
				}
			}
		}
		
		return $data;
	}
	
	public function storeFeatureZip($bytes,$parameters){
		return $this->storeBytes(self::DB_NAME_FEATURE_ZIP, $bytes, $parameters);
	}
	
	public function getFeatureZipById($id){
		return $this->getFileById(self::DB_NAME_FEATURE_ZIP, $id);
	}
	
	public function delFeatureZipById($id){
		$this->removeFileById(self::DB_NAME_FEATURE_ZIP, $id);
	}
}